import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from '@tarojs/components';

import { getUserInfo } from '../../api/user';
import { userLoginLimit } from '../../contexts/store';
import { UserInfoPreset } from '../../contexts/presets';
import { useAppContext } from '../../contexts/AppContext';
import { DataErrorView } from '../../components/dataError';
import { removeToken, getToken } from '../../contexts/store';
import { UserAvatarImage } from '../../components/userAvatar';
import { DataLoadingView } from '../../components/dataLoading';
import { getCarProgressStatisticsApi } from '../../api/myself';
import { CarProgressStatisticsItem } from '../../types/myself';

import './index.scss';

/**
 * 个人中心页面组件
 * 展示用户信息、功能菜单和学习进度
 */
const MyPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const { userInfo, setUserInfo } = useAppContext();
  const userAvatar = userInfo?.avatar;
  const [carSubject, setCarSubject] = useState<CarProgressStatisticsItem>({ total: 0, completed: 0, subjects: [] });
  const [pulseIndex, setPulseIndex] = useState<number>(0);
  const [userPoints, setUserPoints] = useState<number>(0);
  const [userKilometers, setUserKilometers] = useState<number>(0);

  /**
   * 处理退出登录逻辑
   * 清除用户信息并跳转到登录页面
   */
  const handleLogout = () => {
    Taro.showModal({
      title: '确认退出登录',
      content: '退出后需要重新登录才能使用完整功能',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确认',
      success: (res) => {
        if (res.confirm) {
          removeToken(setUserInfo);
          Taro.navigateTo({ url: '/pages/login/index' });
        }
      }
    });
  };

  /**
   * 获取学车进度数据
   */
  const getCarProgress = async () => {
    try {
      const res = await getCarProgressStatisticsApi();
      if (res.code === 200) {
        setCarSubject(res.data);
      } else {
        console.log('获取学车进度失败');
      }
    } catch (error) {
      console.error('获取学车进度失败:', error);
    }
  };

  /**
   * 设置科目进度卡片的脉冲动画
   */
  useEffect(() => {
    const timer = setInterval(() => {
      setPulseIndex((prev) => (prev + 1) % (carSubject?.subjects?.length || 1));
    }, 2000);
    return () => clearInterval(timer);
  }, [carSubject]);

  const fetchUserInfo = async () => {
    const token = getToken();
    if (!token) {
      setUserInfo(UserInfoPreset);
      setCarSubject({ total: 20, completed: 0, subjects: [
        {
            "name": "科目一",
            "total": 7,
            "completed": 0,
            "status": 0,
            "steps": []
        },
        {
            "name": "科目二",
            "total": 4,
            "completed": 0,
            "status": 0,
            "steps": []
        },
        {
            "name": "科目三",
            "total": 4,
            "completed": 0,
            "status": 0,
            "steps": []
        },
        {
            "name": "科目四",
            "total": 5,
            "completed": 0,
            "status": 0,
            "steps": []
        }
      ]});
      return
    }
    try {
      setLoading(true);
      await getUserInfo().then((userInfoResponse) => {
        if (userInfoResponse.code === 200 && userInfoResponse.data) {
          setUserInfo({ ...userInfoResponse.data, updateTime: new Date().getTime() });
          // 获取学车进度（仅针对学员角色）
          if (userInfoResponse.data.role === 100) {
            getCarProgress();
          }
        }else {
          setUserInfo(UserInfoPreset);
          Taro.showToast({
            icon: 'error',
            title: '获取用户信息失败',
          })
        }
      });
    } catch (error) {
      console.error('获取用户信息失败:', error);
      Taro.showToast({
        icon: 'error',
        title: '获取用户信息失败',
      })
    } finally {
      setLoading(false);
    }
  };

  /**
   * 组件加载时获取用户信息和学习进度
   */
  useEffect(() => {
    fetchUserInfo();
  }, []);

  /**
   * 处理功能菜单点击
   */
  const handleMenuClick = (route: string) => {
    if(!userLoginLimit('获取个人内容，需登录服务')) return;
    Taro.navigateTo({ url: route });
  };

  /**
   * 处理科目卡片点击，跳转到对应的进度条界面
   */
  const handleSubjectClick = (subjectName: string) => {
    // 跳转到学习进度页面，并传递科目信息作为参数
    Taro.navigateTo({
      url: `/pages/user-progress/index?tab=${['', '科目一', '科目二', '科目三', '科目四'].indexOf(subjectName)}`
    });
  };

  /**
   * 加载中状态
   */
  if (loading) {
    return (
      <DataLoadingView />
    );
  }

  /**
   * 用户信息获取失败状态
   */
  if (!userInfo) {
    return (
      <DataErrorView
        title="获取用户信息失败"
        content=""
        buttonText="登录"
        onClickFunc={() => Taro.navigateTo({ url: '/pages/login/index' })}
      />
    );
  }

  return (
    <View className="page-container">
      <View className="page-content">
        {/* 用户信息区域 */}
        <View className="user-info-section">
          <View className="user-info-content">
            {/* 头像上传区域 */}
            <View className="avatar-section">
              <View className="user-avatar-placeholder">
                <UserAvatarImage
                  isTourist={userInfo.role === 0}
                  avatar={userInfo.avatar || ''}
                  user_id={Number(userInfo.id) || 0}
                  user_name={userInfo.username || '游客'}
                  class_name="avatar-full-fit"
                />
              </View>
            </View>

            {/* 用户名和ID区域 */}
            <View className="user-details-section">
              <View className="username-container">
                <Text className="user-name">{userInfo.username}</Text>
              </View>
              <Text className="user-id">学员ID: {userInfo.id}</Text>
            </View>
          </View>
          <View>
            {(userInfo.id && Number(userInfo.id))?(
              <Button onClick={handleLogout} size='mini' type='default' className='logout-btn'>退出登录</Button>  
            ):(
              <Button onClick={() => Taro.navigateTo({ url: '/pages/login/index' })} size='mini' type='primary' className='my-login-btn' plain>登录</Button>
            )}
          </View>
        </View>

        {/* 学习进度区域 */}
        {carSubject && carSubject.subjects && carSubject.subjects.length > 0 && (
          <View className="car-subject-progress">
            <View className="progress-header">
              <Text className="progress-title text-base">学车进度</Text>
            </View>

            {/* 进度条 */}
            <View className="progress-bar-container">
              <View
                className="progress-bar"
                style={{ width: `${Math.round((carSubject.completed / carSubject.total) * 100)}%` }}
              />
              <Text className="progress-text text-md">
                {carSubject.completed}/{carSubject.total}
              </Text>
              <View
                className="progress-car-icon"
                style={{ left: `${carSubject.completed?Math.round((carSubject.completed / carSubject.total) * 100):40}%` }}
              >
                <MaterialIcons name="directions-car" color='#ff4d4f' size={16} />
              </View>
            </View>

            {/* 科目进度卡片 */}
            <View className="subject-cards">
              {carSubject.subjects.map((subject, index) => (
                <View
                  key={subject.name}
                  className={`subject-card ${index === pulseIndex ? 'pulse' : ''} ${subject.status === 1 ? 'completed' : 'in-progress'}`}
                  onClick={() => handleSubjectClick(subject.name)}
                  style={{ cursor: 'pointer' }}
                >
                  <Text className="my-subject-name">{subject.name}</Text>
                  <View className="subject-progress-text">
                    <Text className="subject-progress">{subject.completed}</Text>
                    <Text className="subject-total">/{subject.total}</Text>
                  </View>
                  {subject.status === 1 && (
                    <View className="completed-mark">
                      <MaterialIcons name="check-circle" color='#9ed900' size={25}/>
                    </View>
                  )}
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 功能菜单网格 */}
        <View className="my-menu-container">
          <View className="my-menu-grid">
            <View className="my-menu-card">
              <View 
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-time-appoint/index')}
              >
                <MaterialIcons name="date-range" className="my-menu-icon" size={32} color='#afd3df'/>
                <Text className="my-menu-text">我的预约</Text>
              </View>
            </View>
            <View className="my-menu-card">
              <View
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-coach/index')}
              >
                <MaterialIcons name="person" className="menu-icon" size={32}  color='#c7e7e6'/>
                <Text className="my-menu-text">我的教练</Text>
              </View>
            </View>
            <View className="my-menu-card">
              <View 
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-progress/index')}
              >
                <MaterialIcons name="book" className="my-menu-icon" size={32}   color='#63bbcf'/>
                <Text className="my-menu-text">学习进度</Text>
              </View>
            </View>
            <View className="my-menu-card">
              <View 
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-course/index')}
              >
                <MaterialIcons name="directions-car" className="my-menu-icon" size={32}  color='#0eb0c9'/>
                <Text className="my-menu-text">考试学习</Text>
              </View>
            </View>
            <View className="my-menu-card">
              <View 
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-examination/index')}
              >
                <MaterialIcons name="schedule" className="my-menu-icon" size={32}  color='#2775b7'/>
                <Text className="my-menu-text">考试安排</Text>
              </View>
            </View>
            <View className="my-menu-card">
              <View 
                className="my-menu-item"
                onClick={() => handleMenuClick('/pages/user-settings/index')}
              >
                <MaterialIcons name="settings" className="my-menu-icon" size={32} color='#1361ab'/>
                <Text className="my-menu-text">设置</Text>
              </View>
            </View>
          </View>
        </View>

         {/* 底部卡片 - 公里数和积分数 */}
        <View className="bottom-cards">
          <View className="bottom-card kilometers-card">
            <View className="bottom-card-content">
              <Text className="bottom-card-title">{userKilometers} 公里</Text>
              <Text className="bottom-card-subtitle">平台服务100公里</Text>
            </View>
          </View>
          
          <View className="bottom-card points-card">
            <View className="bottom-card-content">
              <Text className="bottom-card-title">{userPoints} 积分</Text>
              <Text className="bottom-card-subtitle">上传积分兑现金</Text>
            </View>
          </View>
        </View>

        {/* 版本信息 */}
        <View className="version-info">
          <Text className="version-text">驾照易考通 v1.0.0</Text>
        </View>
      </View>
    </View>
  );
};

export default MyPage;